package com.epmis.epmis.controller;

import com.epmis.epmis.Service.impl.MailService;
import com.epmis.epmis.pojo.UsersBo;
import com.epmis.epmis.utils.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Controller
public class MailController {
    @Autowired
    private MailService mailService;

    @CrossOrigin
    @PostMapping(value = "/api/mail")
    @ResponseBody
    public RestResponse<String> getCheckCode(@RequestBody UsersBo usersBo){
        RestResponse restResponse = new RestResponse();
        String checkCode = String.valueOf(new Random().nextInt(899999) + 100000);
        //构建邮箱消息
        String message = "您的验证码为："+ checkCode + ",该验证码在5分钟之内有效，请勿泄漏于他人。";
        try {
            //发送消息
            mailService.sendSimpleMail(usersBo.getEmail(), "验证码", message);
        }catch (Exception e){
            restResponse.setData(e);
            restResponse.setEcode(checkCode);
            return restResponse;
        }
        long date = new Date().getTime();
        restResponse.setData(checkCode);
        restResponse.setEcode(checkCode);
        restResponse.setDate(date);
        restResponse.setStatus(true);
        return restResponse;
    }
}
